﻿/*
 * Copyright (C) 2013 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

using UnityEngine;
using System.Collections;
using UnityEngine.SocialPlatforms;

public class GameManager : MonoBehaviour {
    // from the Developer Console:
    private const string NotACompleteDisasterAchievementId = "CgkI9qnBz_4LEAIQAQ";
    private const string LeaderboardId = "CgkI9qnBz_4LEAIQAg";

    private bool mUnlockedNotACompleteDisasterAchievement = false;

    public GameObject[] Complexes; // set by editor

    public enum GameMode { MainMenu, Playing, GameOver };

    private int score = 0;
    public int Score { get { return score; } }

    private GameMode mode = GameMode.MainMenu;
    public GameMode Mode { get { return mode; } }

    public static GameManager Instance {
        get {
            return GameObject.FindGameObjectWithTag("GameManagerTag").GetComponent<GameManager>();
        }
    }

    public void AddScore(int x) {
        score += x;

        if (!mUnlockedNotACompleteDisasterAchievement && Social.localUser.authenticated) {
            // unlock the "not a complete disaster" achievement
            Debug.Log("Unlocking the 'Not a complete disaster' achivement.");
            Social.Active.ReportProgress(NotACompleteDisasterAchievementId, 100, success => {});
            mUnlockedNotACompleteDisasterAchievement = true;
        }
    }

    public void GameOver() {
        if (mode == GameMode.GameOver) return;

        mode = GameMode.GameOver;

        // submit score to the leaderboard
        if (Social.localUser.authenticated) {
            Debug.Log("Submitting score to leaderboard: " + score);
            Social.Active.ReportScore(score, LeaderboardId, success => {});
        }
    }

    public void StartPlaying() {
        mode = GameMode.Playing;
    }

    public void Restart() {
        Application.LoadLevel(Application.loadedLevelName);
    }

    void Update() {
        CheckGameOver();
    }

    void CheckGameOver() {
        foreach (GameObject o in Complexes) {
            if (o.GetComponent<ComplexController>().Alive) return;
        }
        GameOver();
    }
}
